package com.jiguang.property.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiguang.property.config.LoginUser;
import com.jiguang.property.dto.UserInfoDTO;
import com.jiguang.property.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils tokenManager;
    @Autowired
    // @Resource(name = "Normal")
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token从请求头中获取
        String token = request.getHeader("token");
        //判断是否为空
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断token是否有效
        boolean b = JwtUtils.checkToken(token);
        if (!b) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token获取userid
        String userId = tokenManager.getUserFromToken(token);
        //从redis中获取用户信息
        String redisKey = "login:" + userId;
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        String cacheObject = (String) redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(cacheObject)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        UserInfoDTO ucenter = new ObjectMapper().readValue(cacheObject.toString(), UserInfoDTO.class);
        LoginUser loginUser = new LoginUser();
        loginUser.setUcenter(ucenter);
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
